<template>
    <div class="my-tree">
        <div class="btn-group m-b-5">
            <button class="btn btn-success btn-xs" @click="_createFolder(currentSelected.node)" :disabled="btns.folder">
                <i v-tooltip.top="'add group'" class="fif fif-folder-add"></i>
            </button>
            <button class="btn btn-info btn-xs" :disabled="btns.file" @click="_createTemplate(currentSelected.node)">
                <i v-tooltip.top="'add template'" class="fif fif-text"></i>
            </button>
            <button class="btn btn-warning btn-xs" :disabled="btns.rename" @click="_renameNode(currentSelected.node)">
                <i v-tooltip.top="'edit'" class="fif fif-edit"></i>
            </button>
            <button class="btn btn-danger btn-xs" :disabled="btns.del" @click="_deleteNode(currentSelected.node)">
                <i v-tooltip.top="'delete'" class="fif fif-delete"></i>
            </button>
        </div>
        <div :id="id" :data="data"></div>
    </div>
</template>

<script>
    // import 'jstree/dist/themes/default/style.min.css'
    // import 'jstree/dist/jstree.min'
    import {loadOpenNodeId, saveOpenNodeId} from "@/cache"
    import swal from 'sweetalert'
    export default {
        name: "Tree",
        props: {
            id: {
                type: String,
                default: 'my-tree'
            },
            data: {
                type: Array,
                default: () => []
            },
            lang: {
                type: String,
                default: 'zh',
            }
        },
        mounted() {
            this.initTree()
        },
        data() {
            return {
                showTemplate: false,
                message: '',
                currentSelected: null,
                btns: {
                    folder: true,
                    file: true,
                    del: true,
                    rename: true,
                }
            }
        },
        methods: {
            initTree() {
                let openIDs = loadOpenNodeId()
                for (let i = 0; i < this.data.length; i++) {
                    if (this.data[i].parent.indexOf('#') !== -1 || openIDs.indexOf(this.data[i].id) !== -1) {
                        this.data[i].state = {}
                        this.data[i].state.opened = true
                    }
                }
                let el = $(`#${this.id}`)
                let instance = el.jstree(true)
                if (instance) {
                    instance.destroy();
                }
                el.jstree({
                    'core': {
                        'data': this.data,
                        "check_callback": true,
                        "dblclick_toggle": false
                    },
                    'contextmenu': {
                        'show_at_node': false,
                        'select_node': false,
                        items: {
                            'create_group': {
                                'label': 'Add Group',
                                'action': (obj) => {
                                    let instance = el.jstree(true);
                                    let selectNode = instance.get_node(obj.reference)
                                    if (selectNode.original.node_type === 'tempalte') return false
                                    this._createFolder(selectNode)
                                }
                            },
                            'create_template': {
                                'label': 'Add Template',
                                'action': (obj) => {
                                    let instance = el.jstree(true);
                                    let selectNode = instance.get_node(obj.reference);
                                    if (selectNode.original.node_type === 'template') return
                                    this._createTemplate(selectNode)
                                }
                            },
                            'rename': {
                                'label': 'Edit',
                                'action': (obj) => {
                                    let instance = el.jstree(true);
                                    let selectNode = instance.get_node(obj.reference);
                                    this._renameNode(selectNode)
                                }
                            },
                            'delete': {
                                'label': 'Delete',
                                'action': (obj) => {
                                    let instance = el.jstree(true);
                                    let selectNode = instance.get_node(obj.reference);
                                    this._deleteNode(selectNode)
                                }
                            }
                        }
                    },
                    "plugins": ["contextmenu", "ui"]
                }).bind('select_node.jstree', (node, selected, events) => {
                    this.$emit('selected', selected)
                    this.currentSelected = selected
                    // can delete node
                    this.btns.del = !selected.node.children.length ? false : true
                    // can add node
                    if (selected.node.original.node_type === 'group') {

                        this.btns.folder = false
                        this.btns.file = false
                    } else {
                        this.btns.folder = true
                        this.btns.file = true
                    }

                    // every node can rename
                    this.btns.rename = false


                }).bind("create_node.jstree", (event, data) => {
                    let instance = el.jstree(true);
                    instance.edit(data.node, data.node.text, (node, status) => {
                        this.$emit('create', node)
                    })
                }).bind("open_node.jstree", (event, data) => {
                    saveOpenNodeId(data.node.id, 'add')
                }).bind("close_node.jstree", (event, data) => {
                    saveOpenNodeId(data.node.id, 'delete')
                }).bind("show_contextmenu.jstree", function (event, data) {

                    if (data.node.original.node_type === 'template') {
                        $('.vakata-context li').each(function () {
                            if ($(this).index() === 0 || $(this).index() === 1) {
                                $(this).addClass('vakata-contextmenu-disabled');
                            }
                        });
                    }

                    // 非叶子节点不可以删除
                    if (data.node.children.length) {
                        $('.vakata-context li').each(function () {
                            if ($(this).index() === 3) {
                                $(this).addClass('vakata-contextmenu-disabled');
                            }
                        });
                    }
                }).bind("dblclick.jstree",  (node, clicked, e) => {
                    swal({
                        text: this.currentSelected.node.text,
                        icon: 'info'
                    })
                })
            },
            _createFolder(par) {
                if (!this.currentSelected) return
                let item = {};
                item['id'] = new Date().getTime()
                item['parent'] = par.id
                item['text'] = "Add Group"
                item['icon'] = "fif fif-folder"
                item['node_type'] = 'group'
                $(`#${this.id}`).jstree(true).create_node(par.id, item)
            },
            _deleteNode(node) {
                if (!node || node.children.length) return
                this.$emit('delete', node)
            },
            _renameNode(node) {
                if (!node) return
                const originalText = node.text;
                if (node.original.node_type === 'group') {
                    $(`#${this.id}`).jstree(true).edit(node, originalText, (node, status) => {
                        if (status && node.text !== originalText) {
                            this.$emit('update', node, originalText)
                        }
                    });
                } else {
                    this.$emit("cancelModal")
                    let textarea = document.createElement("textarea");
                    textarea.rows = "4"
                    textarea.className = "form-control reply-template"
                    textarea.value = originalText
                    swal({
                        content: textarea,
                        icon: 'info',
                        button: {
                            text: "Update",
                            closeModal: true,
                        },
                    }).then( (value) => {
                        if (value && textarea.value !== originalText) {
                            if (!textarea.value.trim().length) {
                                return $.toast({
                                    heading: 'Type Something',
                                    position: 'top-right',
                                    loaderBg: '#ff6849',
                                    icon: 'error',
                                })
                            }
                            node.text = textarea.value
                            this.$emit('update', node, originalText)
                        }
                        this.$emit("showModal")
                    })
                }

            },
            _createTemplate(node) {
                this.$emit("cancelModal")
                let textarea = document.createElement("textarea");
                textarea.rows = "4"
                textarea.className = "form-control reply-template"
                textarea.value = ""
                swal({
                    content: textarea,
                    icon: 'info',
                    button: {
                        text: "Add!",
                        closeModal: true,
                    },
                }).then( (value) => {
                    this.$emit("showModal")
                    if (value && !textarea.value.trim().length) {
                        return $.toast({
                            heading: 'Require Something',
                            position: 'top-right',
                            loaderBg: '#ff6849',
                            icon: 'error',
                        })
                    }
                    let item = {};
                    item['id'] = new Date().getTime()
                    item['text'] = textarea.value
                    item['icon'] = "fif fif-text"
                    item['original'] = {}
                    item['original']['parent'] = node.id
                    item['original']['node_type'] = 'template'
                    this.$emit('create', item)
                })
            }
        },
        watch: {
            data() {
                this.initTree()
            }
        }
    }
</script>

<style lang="stylus">
    .jstree-default-contextmenu
        z-index: 9999 !important
    .jstree-leaf
        min-width : 100%
        text-overflow : ellipsis;
        white-space : nowrap;
        overflow: hidden;
</style>